package com.djf.djfcs.controller;

import com.djf.djfcs.entity.Product;
import com.djf.djfcs.mapper.ProductMapper;

import com.djf.djfcs.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 商品测试控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/test/products")
@Api(tags = "商品测试接口")
@RequiredArgsConstructor
public class ProductTestController {

    private final IProductService productService;

    @Autowired
    private ProductMapper productMapper;
    
    // 预定义的商品数据
    private static final String[] PRODUCT_NAMES = {
        "iPhone 15 Pro", "iPhone 15", "iPhone 14 Pro Max", "iPhone 14", "iPhone 13",
        "MacBook Pro 16", "MacBook Air 15", "MacBook Pro 14", "MacBook Air 13",
        "iPad Pro 12.9", "iPad Air", "iPad mini", "iPad 10.9",
        "Apple Watch Ultra 2", "Apple Watch Series 9", "Apple Watch SE",
        "AirPods Pro 2", "AirPods 3", "AirPods Max",
        "小米14 Pro", "小米14", "小米13 Ultra", "小米13 Pro", "小米13",
        "Redmi Note 13 Pro", "Redmi K70 Pro", "Redmi K70",
        "华为Mate 60 Pro", "华为Mate 60", "华为P60 Pro", "华为P60",
        "华为nova 12 Pro", "华为nova 12", "华为MatePad Pro",
        "OPPO Find X7 Ultra", "OPPO Find X7 Pro", "OPPO Find X7",
        "OPPO Reno11 Pro", "OPPO Reno11", "OnePlus 12", "OnePlus 11",
        "vivo X100 Pro", "vivo X100", "vivo S18 Pro", "vivo S18",
        "三星Galaxy S24 Ultra", "三星Galaxy S24+", "三星Galaxy S24",
        "ThinkPad X1 Carbon", "ThinkPad T14", "ThinkPad E14",
        "联想小新Pro 16", "联想拯救者Y9000P", "联想YOGA Pro 14s",
        "戴尔XPS 13", "戴尔灵越14", "戴尔游匣G15",
        "惠普战66", "惠普暗影精灵9", "惠普ENVY 13",
        "华硕天选4", "华硕无畏Pro15", "华硕ROG魔霸7",
        "Surface Laptop 5", "Surface Pro 9", "Surface Studio 2+"
    };
    
    private static final String[] CATEGORIES = {
        "手机", "笔记本电脑", "平板电脑", "智能手表", "耳机音响", "台式电脑", "显示器", "键鼠外设"
    };
    
    private static final String[] BRANDS = {
        "Apple", "小米", "华为", "OPPO", "vivo", "三星", "OnePlus", "联想", "戴尔", "惠普", "华硕", "微软"
    };
    
    private static final String[] DESCRIPTIONS = {
        "高性能旗舰产品，搭载最新处理器",
        "轻薄便携，适合商务办公",
        "游戏专用，强劲性能释放",
        "学生首选，性价比超高",
        "专业设计，创作者必备",
        "时尚外观，年轻人喜爱",
        "续航持久，移动办公利器",
        "拍照神器，记录美好时光",
        "音质出众，沉浸式体验",
        "智能科技，引领未来"
    };
    
    private static final String[] TENANT_IDS = {
        "tenant001", "tenant002", "tenant003", "tenant004", "tenant005"
    };

    @PostMapping("/generate")
    @ApiOperation("批量生成商品测试数据")
    public String generateProducts(
            @ApiParam(value = "生成数量", required = true, example = "100")
            @RequestParam("count") Integer count) {
        
        if (count == null || count <= 0) {
            return "生成数量必须大于0";
        }
        
        if (count > 10000) {
            return "单次生成数量不能超过10000";
        }
        
        try {
            List<Product> products = new ArrayList<>();
            Random random = new Random();
            
            for (int i = 0; i < count; i++) {
                Product product = new Product();
                
                // 生成商品编码
                product.setProductCode("PROD" + String.format("%06d", System.currentTimeMillis() % 1000000 + i));
                
                // 随机选择商品名称
                String baseName = PRODUCT_NAMES[random.nextInt(PRODUCT_NAMES.length)];
                product.setProductName(baseName + (i > 0 ? " (" + (i + 1) + ")" : ""));
                
                // 随机选择分类和品牌
                product.setCategory(CATEGORIES[random.nextInt(CATEGORIES.length)]);
                product.setBrand(BRANDS[random.nextInt(BRANDS.length)]);
                
                // 生成随机价格 (100-50000)
                BigDecimal price = BigDecimal.valueOf(100 + random.nextDouble() * 49900)
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
                product.setPrice(price);
                
                // 生成随机库存 (0-1000)
                product.setStock(random.nextInt(1001));
                
                // 随机状态 (90%概率为ACTIVE)
                product.setStatus(random.nextDouble() < 0.9 ? "ACTIVE" : "INACTIVE");
                
                // 随机描述
                product.setDescription(DESCRIPTIONS[random.nextInt(DESCRIPTIONS.length)]);
                
                // 生成图片URL
                product.setImageUrl("https://example.com/images/product_" + (i + 1) + ".jpg");
                
                // 随机租户ID
                product.setTenantId(TENANT_IDS[random.nextInt(TENANT_IDS.length)]);
                
                // 设置创建时间（随机分布在最近30天内）
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime createTime = now.minusDays(random.nextInt(30))
                    .minusHours(random.nextInt(24))
                    .minusMinutes(random.nextInt(60));
                product.setCreateTime(createTime);
                product.setUpdateTime(createTime);
                
                products.add(product);
                
                // 每1000条批量插入一次
                if (products.size() >= 1000) {
                    productService.saveBatch(products);
                    products.clear();
                    log.info("已生成 {} 条商品数据", i + 1);
                }
            }
            
            // 插入剩余数据
            if (!products.isEmpty()) {
                productService.saveBatch(products);
            }
            
            log.info("批量生成商品数据完成，共生成 {} 条记录", count);
            return String.format("成功生成 %d 条商品测试数据", count);
            
        } catch (Exception e) {
            log.error("生成商品测试数据失败", e);
            return "生成失败：" + e.getMessage();
        }
    }
    
    @PostMapping("/generate-by-category")
    @ApiOperation("按分类生成商品测试数据")
    public String generateProductsByCategory(
            @ApiParam(value = "分类名称", required = true, example = "手机")
            @RequestParam("category") String category,
            @ApiParam(value = "生成数量", required = true, example = "50")
            @RequestParam("count") Integer count) {
        
        if (count == null || count <= 0) {
            return "生成数量必须大于0";
        }
        
        if (count > 5000) {
            return "单次生成数量不能超过5000";
        }
        
        try {
            List<Product> products = new ArrayList<>();
            Random random = new Random();
            
            for (int i = 0; i < count; i++) {
                Product product = new Product();
                
                // 生成商品编码
                product.setProductCode(category.toUpperCase() + String.format("%05d", System.currentTimeMillis() % 100000 + i));
                
                // 根据分类选择合适的商品名称
                String[] categoryProducts = getCategoryProducts(category);
                String baseName = categoryProducts[random.nextInt(categoryProducts.length)];
                product.setProductName(baseName + (i > 0 ? " 第" + (i + 1) + "款" : ""));
                
                // 设置指定分类
                product.setCategory(category);
                
                // 根据分类选择合适的品牌
                String[] categoryBrands = getCategoryBrands(category);
                product.setBrand(categoryBrands[random.nextInt(categoryBrands.length)]);
                
                // 根据分类生成合理的价格范围
                BigDecimal price = generateCategoryPrice(category, random);
                product.setPrice(price);
                
                // 生成随机库存
                product.setStock(random.nextInt(501) + 50); // 50-550
                
                // 状态
                product.setStatus("ACTIVE");
                
                // 描述
                product.setDescription("专业" + category + "产品，" + DESCRIPTIONS[random.nextInt(DESCRIPTIONS.length)]);
                
                // 图片URL
                product.setImageUrl("https://example.com/images/" + category + "_" + (i + 1) + ".jpg");
                
                // 租户ID
                product.setTenantId(TENANT_IDS[random.nextInt(TENANT_IDS.length)]);
                
                // 创建时间
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime createTime = now.minusDays(random.nextInt(7))
                    .minusHours(random.nextInt(24));
                product.setCreateTime(createTime);
                product.setUpdateTime(createTime);
                
                products.add(product);
            }
            
            productService.saveBatch(products);
            
            log.info("按分类生成商品数据完成，分类：{}，共生成 {} 条记录", category, count);
            return String.format("成功生成 %s 分类的 %d 条商品测试数据", category, count);
            
        } catch (Exception e) {
            log.error("按分类生成商品测试数据失败", e);
            return "生成失败：" + e.getMessage();
        }
    }
    
    @DeleteMapping("/clear")
    @ApiOperation("清空所有测试数据")
    public String clearTestData() {
        try {
            // 这里可以添加清空逻辑，比如删除所有测试数据
            // productService.remove(new QueryWrapper<>());
            return "清空测试数据功能待实现（为安全考虑）";
        } catch (Exception e) {
            log.error("清空测试数据失败", e);
            return "清空失败：" + e.getMessage();
        }
    }
    
    /**
     * 根据分类获取对应的商品名称
     */
    private String[] getCategoryProducts(String category) {
        switch (category) {
            case "手机":
                return new String[]{"iPhone 15 Pro", "小米14 Pro", "华为Mate 60 Pro", "OPPO Find X7", "vivo X100", "三星Galaxy S24"};
            case "笔记本电脑":
                return new String[]{"MacBook Pro", "ThinkPad X1", "联想小新Pro", "戴尔XPS", "惠普战66", "华硕天选"};
            case "平板电脑":
                return new String[]{"iPad Pro", "iPad Air", "华为MatePad", "小米平板", "Surface Pro"};
            case "智能手表":
                return new String[]{"Apple Watch", "华为Watch", "小米手表", "OPPO Watch", "三星Galaxy Watch"};
            case "耳机音响":
                return new String[]{"AirPods Pro", "小米耳机", "华为FreeBuds", "索尼耳机", "Beats耳机"};
            default:
                return PRODUCT_NAMES;
        }
    }
    
    /**
     * 根据分类获取对应的品牌
     */
    private String[] getCategoryBrands(String category) {
        switch (category) {
            case "手机":
                return new String[]{"Apple", "小米", "华为", "OPPO", "vivo", "三星", "OnePlus"};
            case "笔记本电脑":
                return new String[]{"Apple", "联想", "戴尔", "惠普", "华硕", "微软"};
            case "平板电脑":
                return new String[]{"Apple", "华为", "小米", "微软", "三星"};
            case "智能手表":
                return new String[]{"Apple", "华为", "小米", "OPPO", "三星"};
            case "耳机音响":
                return new String[]{"Apple", "小米", "华为", "索尼", "Beats"};
            default:
                return BRANDS;
        }
    }
    
    /**
     * 根据分类生成合理的价格
     */
    private BigDecimal generateCategoryPrice(String category, Random random) {
        double basePrice;
        double range;
        
        switch (category) {
            case "手机":
                basePrice = 2000;
                range = 8000;
                break;
            case "笔记本电脑":
                basePrice = 3000;
                range = 15000;
                break;
            case "平板电脑":
                basePrice = 1500;
                range = 6000;
                break;
            case "智能手表":
                basePrice = 500;
                range = 3000;
                break;
            case "耳机音响":
                basePrice = 200;
                range = 2000;
                break;
            default:
                basePrice = 500;
                range = 5000;
        }
        
        double price = basePrice + random.nextDouble() * range;
        return BigDecimal.valueOf(price).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}